package cn.lingyangwl.agile.system.listener;

import cn.lingyangwl.agile.log.*;
import cn.lingyangwl.agile.system.model.rqrs.log.*;
import cn.lingyangwl.agile.system.service.*;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author shenguangyang
 */
@Slf4j
@Component
@RabbitListener(bindings = {
        @QueueBinding(
                value = @Queue(value = AccessLogMQ.QUEUE, durable = "false"), key = AccessLogMQ.KEY,
                exchange = @Exchange(value = AccessLogMQ.EXCHANGE, type = ExchangeTypes.TOPIC))
})
public class AccessLogSaveListener {
    @Resource
    private SysAccessLogService logService;

    @RabbitHandler
    public void onMessage(@Payload String msg, Channel channel, Message message) {
        log.info("listener-saveAccessLog, msg: {}", msg);
        try {
            AccessLogSaveReq msgPayload = AccessLogMQ.parse(msg, AccessLogSaveReq.class);
            if (Objects.isNull(msgPayload.getTenantId())) {
                return;
            }
            logService.save(msgPayload);
        } catch (Exception e) {
            log.error("error: ", e);
            throw e;
        }
    }
}
